#include "timelcdnumberview.h"
#include <QDateTime>
#include <QMouseEvent>
#include <QApplication>
#include <QHBoxLayout>


int TimeLcdView::m_id = qRegisterMetaType<TimeLcdView*>();

TimeLcdView::TimeLcdView(QWidget *parent)
    :ViewObject(parent)
    ,m_timer(NULL)
    ,m_labelTime(NULL)
    ,m_timeViewParam(NULL)
{
     setAttribute(Qt::WA_DeleteOnClose);
     m_labelTime = new QLCDNumber(this);
     m_labelTime->setSizePolicy(QSizePolicy::Expanding, QSizePolicy::Expanding);
     m_labelTime->setFrameShape(QFrame::NoFrame);
     m_labelTime->setSegmentStyle(QLCDNumber::Flat);
     QFont font;
     font.setBold(true);
     font.setPixelSize(50);
     font.setPointSize(50);
     font.setWeight(QFont::Bold);
     m_labelTime->setDigitCount(5);//
     m_labelTime->setFont(font);

     QHBoxLayout *layout = new QHBoxLayout;
     layout->addWidget(m_labelTime, 0, Qt::AlignCenter);
     layout->setContentsMargins(0, 0, 0, 0);
     setContentsMargins(0, 0, 0, 0);
     setLayout(layout);
#ifdef __linux__
    setFocusPolicy(Qt::NoFocus);
#else
    setFocusPolicy(Qt::StrongFocus);
#endif

     if (m_objectParam == NULL)
     {
         m_objectParam = new ParamObject;
     }

     if(m_timer == NULL)
     {
         m_timer = new QTimer(this);
     }

     if(m_timeViewParam == NULL)
     {
         m_timeViewParam = new TimeLcdViewParam;
     }

    connect(m_timer, SIGNAL(timeout()), this, SLOT(TimeOutSlot()));
}


TimeLcdView::~TimeLcdView()
{
    DestoryObject();
}

void TimeLcdView::ShowObject(QWidget* parent, QString prefix, ProtocolData * ptr_data)
{
    Q_UNUSED(prefix);
    Q_UNUSED(ptr_data);

    if(m_timeViewParam == NULL)
    {
        return;
    }

    if (m_objectParam == NULL )
    {
        return;
    }

    setParent(parent);
    QStringList tmplist;

    QDateTime datetime = QDateTime::currentDateTime();

    if (m_timeViewParam->m_time.m_timeFormat != "")
    {
        m_labelTime->display(datetime.toString(m_timeViewParam->m_time.m_timeFormat));
    }
    else
    {
        m_labelTime->display(datetime.toString("yyyy MM dd hh:mm"));
    }

    if (m_timeViewParam->m_time.m_timeStyle !="")
    {
        QStringList format_list = m_timeViewParam->m_time.m_timeStyle.split("\n");
        QString format_qss = styleSheet();
        for (int i = 0; i < format_list.size(); i++)
        {

            if (format_list.at(i).contains(";"))
            {
                format_qss.append(format_list.at(i));
            }
            else
            {
                QFont f;
                if (f.fromString(format_list.at(i)))
                    m_labelTime->setFont(f);
            }
        }
        setStyleSheet(format_qss);
    }

    TimeOutSlot();
    m_timer->start(300);

    location(m_objectParam->GetX(), m_objectParam->GetY(), m_objectParam->GetWidth(), m_objectParam->GetHeight());
    m_labelTime->setFixedSize(size());

    show();
}

void TimeLcdView::HideObject()
{
    setParent(NULL);
    if(m_timer->isActive())
    {
        m_timer->stop();
    }
    hide();
}

void TimeLcdView::DestoryObject()
{
    HideObject();
    if(m_timeViewParam != NULL)
    {
        delete m_timeViewParam;
        m_timeViewParam = NULL;
    }

    if (m_objectParam != NULL)
    {
        delete  m_objectParam;
        m_objectParam = NULL;
    }

    close();

}

void TimeLcdView::GetAttribute(std::string& attribute)
{   
    std::string jsonStr;
    Json::Value base;
    Json::StreamWriterBuilder writerBuilder;
    std::ostringstream os;

    base["zindex"] = QString::number(m_objectParam->GetIndex()).toStdString();
    base["stid"] = QString::number(m_objectParam->GetStId()).toStdString();
    base["idtype"] = m_objectParam->GetStIdType().toStdString();
    base["x"] = QString::number(m_objectParam->GetX()).toStdString();
    base["y"] = QString::number(m_objectParam->GetY()).toStdString();
    base["w"] = QString::number(m_objectParam->GetWidth()).toStdString();
    base["h"] = QString::number(m_objectParam->GetHeight()).toStdString();
    base["name"] = m_objectParam->GetName().toStdString();

    base["timeformat"] = m_timeViewParam->m_time.m_timeFormat.toStdString();
    base["timestyle"] = m_timeViewParam->m_time.m_timeStyle.toStdString();
    std::unique_ptr<Json::StreamWriter> jsonWriter(writerBuilder.newStreamWriter());
    jsonWriter->write(base, &os);
    jsonStr = os.str();

    attribute = jsonStr;

}

void TimeLcdView::SetAttribute(std::string jsonStr)
{
    bool res;
    JSONCPP_STRING errs;
    Json::Value root;
    Json::CharReaderBuilder readerBuilder;
    std::unique_ptr<Json::CharReader> const jsonReader(readerBuilder.newCharReader());
    res = jsonReader->parse(jsonStr.c_str(), jsonStr.c_str()+jsonStr.length(), &root, &errs);

    if (!res || !errs.empty())
    {
         LOG_QDEBUG<<__FUNCTION__<<"json parse faild"<<QString::fromStdString(errs);
    }

    if(CheckJsonValueType(root,"zindex",Json::stringValue))
    {
       m_objectParam->SetIndex(QString::fromStdString(root["zindex"].asString()).toInt());
    }
    if(CheckJsonValueType(root,"stid",Json::stringValue))
    {
       m_objectParam->SetStId(QString::fromStdString(root["stid"].asString()).toInt());
    }

    if(CheckJsonValueType(root,"x",Json::stringValue))
    {
        m_objectParam->SetX(QString::fromStdString(root["x"].asString()).toInt());
    }

    if(CheckJsonValueType(root,"y",Json::stringValue))
    {
        m_objectParam->SetY(QString::fromStdString(root["y"].asString()).toInt());
    }

    if(CheckJsonValueType(root,"w",Json::stringValue))
    {
         m_objectParam->SetWidth(QString::fromStdString(root["w"].asString()).toInt());
    }

    if(CheckJsonValueType(root,"h",Json::stringValue))
    {
         m_objectParam->SetHeight(QString::fromStdString(root["h"].asString()).toInt());
    }

    if(CheckJsonValueType(root,"name",Json::stringValue))
    {
         m_objectParam->SetName(QString::fromStdString(root["name"].asString()));
    }

    if(CheckJsonValueType(root,"timeformat",Json::stringValue))
    {
        m_timeViewParam->m_time.m_timeFormat = QString::fromStdString(root["timeformat"].asString());
    }

    if(CheckJsonValueType(root,"timestyle",Json::stringValue))
    {
        m_timeViewParam->m_time.m_timeStyle = QString::fromStdString(root["timestyle"].asString());
    }
    if (CheckJsonValueType(root, "idtype", Json::stringValue))
    {
        m_objectParam->SetStIdType(QString::fromStdString(root["idtype"].asString()));
    }
}


void TimeLcdView::ParseXML(QDomElement* xmlDomEle)
{
    if(m_timeViewParam == NULL)
    {
        m_timeViewParam = new TimeLcdViewParam;
    }
    m_objectParam->SetIndex((xmlDomEle->attribute("zindex","0")).toInt());
    m_objectParam->SetStId((xmlDomEle->attribute("stid","0")).toInt());
    m_objectParam->SetX((xmlDomEle->attribute("x","0")).toInt());
    m_objectParam->SetY((xmlDomEle->attribute("y","0")).toInt());
    m_objectParam->SetWidth((xmlDomEle->attribute("w","0")).toInt());
    m_objectParam->SetHeight((xmlDomEle->attribute("h","0")).toInt());
    m_objectParam->SetName(xmlDomEle->attribute("name",""));

    QDomNodeList paramlist = xmlDomEle->childNodes();
    for(int listcnt = 0; listcnt < paramlist.count(); listcnt++)
    {
        QDomElement param = paramlist.item(listcnt).toElement();
        if(param.isComment()||param.isNull())
        {
            continue;
        }
        QString temp = param.attribute("timeformat", "");
        if(temp != "")
        {
            m_timeViewParam->m_time.m_timeFormat = temp;
        }
        temp = param.attribute("timestyle", "");
        if(temp != "")
        {
            m_timeViewParam->m_time.m_timeStyle = temp;
        }
    }

}

void TimeLcdView::PacketXML(QDomElement* dom)
{
    QDomDocument document;
    *dom = document.createElement("item");
    dom->setAttribute("type", m_objectParam->GetObjectName());
    dom->setAttribute("zindex",QString::number(m_objectParam->GetIndex()));
    dom->setAttribute("stid",QString::number(m_objectParam->GetStId()));
    dom->setAttribute("x",QString::number(m_objectParam->GetX()));
    dom->setAttribute("y",QString::number(m_objectParam->GetY()));
    dom->setAttribute("w",QString::number(m_objectParam->GetWidth()));
    dom->setAttribute("h",QString::number(m_objectParam->GetHeight()));
    dom->setAttribute("name",m_objectParam->GetName());

    QDomElement dom2 = document.createElement("param");
    dom2.setAttribute("timeformat", m_timeViewParam->m_time.m_timeFormat);
    dom->appendChild(dom2);

    QDomElement dom3 = document.createElement("param");
    dom3.setAttribute("timestyle", m_timeViewParam->m_time.m_timeStyle);
    dom->appendChild(dom3);

}

void TimeLcdView::TimeOutSlot()
{
    QString tmpstr;
    QDateTime datetime;
    if(NULL != m_labelTime)
    {
        datetime = QDateTime::currentDateTime();
        tmpstr = datetime.toString("yyyy MM dd hh:mm");
        //2018.11.11 以后为有效日期  其他不显示
        if(datetime > QDateTime::fromString("2018-11-11 00:00:00","yyyy-MM-dd hh:mm:ss") )
        {
            if(tmpstr != m_timeStr)
            {
                m_timeStr = tmpstr;
                m_labelTime->display(m_timeStr);
            }
        }
        else
        {
            m_labelTime->display("");
        }

    }
}
